package service

import (
	"github.com/gin-gonic/gin"
	"log"
	"micro-chat/config"
	"micro-chat/internal/model"
	"micro-chat/internal/request"
	"micro-chat/pkg"
	"net/http"
	"time"
)

func RegisterUser(c *gin.Context) {
	var req request.RegisterUserForm

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "验证失败",
		})
		return
	}

	var user model.User
	var sms model.SmsVerify

	get := config.RDB.Get(config.Ctx, "sendSms"+req.Phone+"register")

	if get.Val() != req.Sms {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "短信验证失败",
		})
	} else {
		//销毁短信
		err := sms.Delete(req.Sms)
		if err != nil {
			log.Println(err)
		}
		config.RDB.Del(config.Ctx, "sendSms"+req.Phone+"register")
	}

	user.Phone = req.Phone

	err := user.LoginUser()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "手机号验证失败",
			"data":    err.Error(),
		})
		return
	}

	if user.Id != 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "账号已存在,请登陆",
		})
		return
	}

	user.Password = pkg.Md5(req.Password)
	user.Nickname = req.Nickname
	err = user.RegisterUser()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "注册失败",
			"data":    err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "注册成功",
		"data":    user.Id,
	})

}

func LoginUser(c *gin.Context) {
	var req request.LoginUserForm

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "验证失败",
		})
		return
	}

	var user model.User
	user.Phone = req.Phone

	err := user.LoginUser()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "手机验证失败",
			"data":    err.Error(),
		})
		return
	}

	if user.Id == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "账号或密码错误",
		})
		return
	}

	if user.Password != pkg.Md5(req.Password) {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    100000,
			"message": "账号或密码错误",
		})
		return
	}

	token := pkg.CreateJwtToken(user.Id)

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "登陆成功",
		"data":    token,
	})

	user.LastLoginTime = time.Now()
	err = user.UpdateUser()
	if err != nil {
		return
	}

}
